<template>
	<div>
		<div class="nav-title flex align-center">
			<p>服务养老组织（机构）</p>
			<div class="primary-btn" @click="drawer = !drawer">选择</div>
		</div>
		<div class="nav-title">
			<p>已选 {{ orgList.length }} 个</p>
		</div>
		<div class="nav-list-item">
			<el-tag v-for="(tag, index) in orgList" :key="index" class="mx-1" closable type="info" @close="handleClose(index,tag)">
				<span class="text-black">{{ tag.organizationName }}</span>
			</el-tag>
		</div>

		<el-drawer v-model="drawer" title="选择服务组织" size="60%" :lock-scroll="false" :modal="true" append-to-body>
			<el-page-header @back="drawer = !drawer">
				<template #content>
					<span class="text-large font-600 mr-3 text-blue"> 请勾选服务组织 </span>
				</template>
			</el-page-header>
			<ElderlyCareInstitution ref="elderlyInstitutionEl" @selection-change="onSelectionChange" :selectedData="selectedData"></ElderlyCareInstitution>
		</el-drawer>
	</div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod/index'
import ElderlyCareInstitution from '../../ElderlyCareInstitution/index.vue'

const elderlyInstitutionEl = ref(null)
const props = defineProps<{
	model?: any
}>()

const emit = defineEmits(['change'])
const drawer = ref(false)

const orgList = ref([])
const selectedData = ref([])
const onSelectionChange = (arr) => {
	// if (selectedData.value.length > arr.length) {
	// 	return
	// }
	orgList.value = [...new Map(arr.map((v: any) => [v.id, v])).values()]
	selectedData.value = orgList.value
	emit('change', orgList.value)
}

const handleClose = async (index,tag) => {
  const indexKey = selectedData.value.findIndex((item) => item.creditCode == tag.creditCode)
  if(indexKey !==-1) {
    selectedData.value.splice(indexKey, 1)
  }
	orgList.value.splice(index, 1)
  elderlyInstitutionEl.value.setToggleSelection(selectedData.value)
	emit('change', orgList.value)
}

const handleGetSelected = () => {
	let orgs = orgList.value.map((item) => item.creditCode)
	if (orgs.length == 0) {
		selectedData.value = []
		return
	}
	let params = { organizationIdList: orgs }
	apiMod.view_dpServiceOrgBase_page(params).then((res) => {
		selectedData.value = res.data.records
	})
}
watchEffect(() => {
	orgList.value = props.model?.organizationJson.map((item) => {
		return {
			organizationName: item.label,
			creditCode: item.value,
		}
	})
	handleGetSelected()
})
</script>

<style scoped lang="scss">
.nav-title {
	font-family: 'Microsoft YaHei Bold';
	font-weight: 700;
	font-size: 20px;
	text-align: left;
	color: #1c1c28;
	.primary-btn {
		margin-left: 10px;
		border: 1px solid #0052d9;
		color: #0052d9;
		background: #fff;
		border-radius: 4px;
		height: 31px;
		font-size: 14px;
		padding: 6px 16px;
		&:hover {
			cursor: pointer;
		}
	}
}
.nav-list-item {
	width: 100%;
	flex-flow: row wrap;
	margin-top: 10px;
	display: flex;
	gap: vw(10);
	font-family: 'Microsoft YaHei';
	font-weight: 400;
	font-size: 14px;
	line-height: 22px;
	text-align: left;
	color: #000;
}
</style>
